/**
 * 
 */
package org.ewaf.framework.velocity.tools;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.view.context.ViewContext;
import org.springframework.util.CollectionUtils;

/**
 * @author peng.sunp
 * 
 */
public class ErrorsViewer{

	private static final String NEW_LINE_SIGN = "<br/>";
	// protected HttpServletRequest request;
	protected Map<String, List<String>> errorMap;
	protected boolean isEmpty = true;

	@SuppressWarnings("unchecked")
	public void init(Object obj) {
		
		
		if (!(obj instanceof ViewContext)) {
			
			throw new IllegalArgumentException(
					
					"Tool can only be initialized with a ViewContext");
		}

		ViewContext context = (ViewContext) obj;
		HttpServletRequest request = context.getRequest();
		try {
			this.errorMap = (Map<String, List<String>>) request
					.getAttribute("fieldErrors");
			this.isEmpty = CollectionUtils.isEmpty(this.errorMap);
		} catch (Exception e) {
			throw new IllegalArgumentException(
					"Tool can only be initialized with a ViewContext");
		}
	}

	public String get(String fieldName) {
		if (this.isEmpty || fieldName == null) {
			return "";
		}
		List<String> message = this.errorMap.get(fieldName);
		if (CollectionUtils.isEmpty(message)) {
			return "";
		}
		StringBuilder result = new StringBuilder(message.get(0));
		for (int i = 1; i < message.size(); i++) {
			result.append(NEW_LINE_SIGN);
			result.append(message.get(1));
		}
		return result.toString();
	}

	public String getAll() {
		if (this.isEmpty) {
			return "";
		}
		StringBuilder result = new StringBuilder();
		for (List<String> list : this.errorMap.values()) {
			for (String msg : list) {
				result.append(NEW_LINE_SIGN);
				result.append(msg);
			}
		}
		return result.substring(NEW_LINE_SIGN.length());
	}

}
